const path = require('path');
const fs = require('fs');
const shelljs = require('shelljs');
const del = require('del');
const ci = require('miniprogram-ci');
const chalk = require('chalk');
const { branch, commitHash, commitMessages } = require('./git-command');
const package = require('../package.json');
const projectConfig = require('../project.config.json');

// check yarn version
require('./check-version');

// delete dist directory
del.sync([path.join(__dirname, '../dist')]);

// install dependencies
shelljs.exec('yarn --registry=https://registry.npm.taobao.org');

// build weapp project
shelljs.exec('yarn run build:weapp');

// upload information
console.log('appid: ', projectConfig.appid);
console.log('publish directory: ', path.join(__dirname, '../dist'));
console.log('publish version: ', package.version);

const descTemplate = `
发布时间: ${new Date().toLocaleString()} ；
发布分支: ${branch}；
最近一次commit: ${commitHash}；
近几次提交的cmmit信息: ${commitMessages}
`;

console.log(descTemplate);

// upload dest directory
(async () => {
  const project = new ci.Project({
    appid: projectConfig.appid,
    type: 'miniProgram',
    projectPath: path.join(__dirname, '../dist'),
    privateKeyPath: path.join(__dirname, './private.wxd304bd4a123f66ef.key'), // TODO 待处理
    ignores: ['node_modules/**/*'],
  });

  const result = await ci.upload({
    project,
    version: package.version,
    desc: descTemplate, // TODO 与git结合
    setting: {
      minify: true,
    },
    robot: 20, // 指定使用哪个哪个ci机器人
    onProgressUpdate: console.log,
  });

  console.log(result);
})();
